package com.levis.huolalarobber.ui;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.levis.huolalarobber.Constant;
import com.levis.huolalarobber.R;
import com.levis.huolalarobber.service.FloatingService;
import com.levis.huolalarobber.service.HuolalaAccessibilityService;
import com.levis.huolalarobber.utils.DeadAppUtil;
import com.levis.huolalarobber.utils.InfoUtil;
import com.levis.huolalarobber.utils.SPutils;
import com.levis.huolalarobber.utils.ToastUtils;
import com.levis.huolalarobber.utils.UuidUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.Date;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Response;

import static android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS;
import static android.provider.Settings.Secure;
import static android.provider.Settings.SettingNotFoundException;

public class MainActivity extends AppCompatActivity {
    final static String TAG = "---HuolalaRobberMainActivity---";
    CheckBox cb_open;
    CheckBox cb_price;
    EditText etMaxPrice, etMinPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPermission();
        initView();
        initData();
        if (!appIsDead()) {
            if (!isAccessibilitySettingsOn(this)) {
                Toast.makeText(getApplicationContext(), "请先开启服务", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ACTION_ACCESSIBILITY_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
        judgeValid();
    }

    private void initData() {
        String imei = (String) SPutils.get(this, Constant.SP_IMEI, "");
        String uuid = (String) SPutils.get(this, Constant.SP_DEV_UUID, "");
        if (!TextUtils.isEmpty(imei)) {
            JPushInterface.setAlias(MainActivity.this, Constant.JPUSH_SEQUENCE, imei);
        }
    }

    private void initView() {
        cb_open = (CheckBox) findViewById(R.id.cb_open);
        if ((boolean) SPutils.get(getApplicationContext(), Constant.SP_OPEN, false)) {
            cb_open.setChecked(true);
        } else {
            cb_open.setChecked(false);
        }
        cb_open.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SPutils.put(MainActivity.this, Constant.SP_OPEN, isChecked);
            }
        });
        etMaxPrice = findViewById(R.id.et_max_price);
        etMinPrice = findViewById(R.id.et_min_price);
        String minPrice = (String) SPutils.get(getApplicationContext(), Constant.SP_MIN_PRICE, "0.00".toString());
        String maxPrice = (String) SPutils.get(getApplicationContext(), Constant.SP_MAX_PRICE, "9999.99".toString());
        etMaxPrice.setText(maxPrice);
        etMinPrice.setText(minPrice);
        cb_price = findViewById(R.id.cb_price);
        if ((boolean) SPutils.get(getApplicationContext(), Constant.SP_OPEN_PRICE, false)) {
            cb_price.setChecked(true);
        } else {
            cb_price.setChecked(false);
        }
        cb_price.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SPutils.put(MainActivity.this, Constant.SP_OPEN_PRICE, isChecked);
                if (TextUtils.isEmpty(etMaxPrice.getText())) {
                    etMaxPrice.setText("9999");
                }
                if (TextUtils.isEmpty(etMinPrice.getText())) {
                    etMinPrice.setText("0");
                }
                SPutils.put(MainActivity.this, Constant.SP_MAX_PRICE, etMaxPrice.getText().toString());
                SPutils.put(MainActivity.this, Constant.SP_MIN_PRICE, etMinPrice.getText().toString());
            }
        });
        etMaxPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                cb_price.setChecked(false);
                SPutils.put(MainActivity.this, Constant.SP_OPEN_PRICE, false);
            }
        });
        etMinPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                cb_price.setChecked(false);
                SPutils.put(MainActivity.this, Constant.SP_OPEN_PRICE, false);
            }
        });
    }

    public void buttonListener(View v) {
        Intent intent = new Intent(MainActivity.this, FloatingService.class);
        switch (v.getId()) {
            case R.id.open_button:
                startService(intent);
                break;
            case R.id.close_button:
                stopService(intent);
                break;
            default:
                break;
        }
    }

    private boolean isAccessibilitySettingsOn(Context mContext) {
        int accessibilityEnabled = 0;
        final String service = getPackageName() + "/"
                + HuolalaAccessibilityService.class.getCanonicalName();
        try {
            accessibilityEnabled = Secure.getInt(mContext
                            .getApplicationContext().getContentResolver(),
                    Secure.ACCESSIBILITY_ENABLED);
            Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled);
        } catch (SettingNotFoundException e) {
            Log.e(TAG,
                    "Error finding setting, default accessibility to not found: "
                            + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(
                ':');
        if (accessibilityEnabled == 1) {
            Log.v(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Secure.getString(mContext
                            .getApplicationContext().getContentResolver(),
                    Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();
                    Log.v(TAG, "-------------- > accessibilityService :: "
                            + accessibilityService + " " + service);
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        Log.v(TAG,
                                "We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
            Log.v(TAG, "***ACCESSIBILITY IS DISABLED***");
        }
        return false;
    }


    @Override
    protected void onResume() {
        super.onResume();
        appIsDead();
        judgeValid();
    }

    private boolean appIsDead() {
        if (DeadAppUtil.appIsDead(this)) {
            SPutils.put(MainActivity.this, Constant.SP_OPEN, false);
            cb_open.setChecked(false);
            cb_open.setEnabled(false);
            showDeadDialog();
            return true;
        } else {
            return false;
        }
    }

    private void judgeValid() {
        String url = "http://www.baidu.com/";
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        Date date = response.headers().getDate("Date");
                        if (date.getTime() > (long) 1533830400 * (long) 1000) {
                            SPutils.put(MainActivity.this, Constant.SP_OPEN, false);
                            cb_open.setChecked(false);
                            cb_open.setEnabled(false);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showAlertDialog();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        SPutils.put(MainActivity.this, Constant.SP_OPEN, false);
                        cb_open.setChecked(false);
                        cb_open.setEnabled(false);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showWebErrorDialog();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        //    设置Title的图标
        builder.setIcon(R.mipmap.ic_launcher);
        //    设置Title的内容
        builder.setTitle("该版本已经过有效期！");
        //    设置Content来显示一个信息
        builder.setMessage("请联系客服续费，8秒后将自动关闭程序！");
        //    设置一个PositiveButton
        builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                System.exit(0);
            }
        });
        builder.setCancelable(false);
        //    显示出该对话框
        builder.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
                System.exit(0);
            }
        }, 8000);
    }

    private void showDeadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        //    设置Title的图标
        builder.setIcon(R.mipmap.ic_launcher);
        //    设置Title的内容
        builder.setTitle("该版本已经被开发者关闭！");
        //    设置Content来显示一个信息
        builder.setMessage("请联系客服咨询详情，8秒后将自动关闭程序！");
        //    设置一个PositiveButton
        builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                System.exit(0);
            }
        });
        builder.setCancelable(false);
        //    显示出该对话框
        builder.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
                System.exit(0);
            }
        }, 8000);
    }

    private void showWebErrorDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        //    设置Title的图标
        builder.setIcon(R.mipmap.ic_launcher);
        //    设置Title的内容
        builder.setTitle("联网检测失败！");
        //    设置Content来显示一个信息
        builder.setMessage("请确保正常联网，8秒后将自动关闭程序！");
        //    设置一个PositiveButton
        builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                System.exit(0);
            }
        });
        builder.setCancelable(false);
        //    显示出该对话框
        builder.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
                System.exit(0);
            }
        }, 8000);
    }


    private void initPermission() {
        AndPermission.with(this)
                .requestCode(200)
                .permission( Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int i, final Rationale rationale) {
                        com.yanzhenjie.alertdialog.AlertDialog.newBuilder(MainActivity.this)
                                .setTitle("请授权")
                                .setMessage("请授权相关权限，否则您将无法正常使用该辅助！")
                                .setPositiveButton("授权", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.resume();
                                    }
                                })
                                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.cancel();
                                        ToastUtils.showLongToast(MainActivity.this, "授权失败，请前往系统设置手动授权,否则无法正常使用部分功能！");
                                    }
                                }).show();
                    }
                }).callback(new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, List<String> grantedPermissions) {
                // Successfully.
                if (requestCode == 200) {
                    String imei = InfoUtil.getIMEI_1(MainActivity.this);
                    if (!TextUtils.isEmpty(imei)) {
                        SPutils.put(MainActivity.this, Constant.SP_IMEI, imei);
                        JPushInterface.setAlias(MainActivity.this, Constant.JPUSH_SEQUENCE, imei);
                    }
                    String uuid = new UuidUtils(MainActivity.this).getDeviceUuid();
                    if (!TextUtils.isEmpty(uuid)) {
                        SPutils.put(MainActivity.this, Constant.SP_DEV_UUID, uuid);
                    }
                }
            }

            @Override

            public void onFailed(int requestCode, List<String> deniedPermissions) {
                // Failure.
                if (requestCode == 200) {
                    ToastUtils.showLongToast(MainActivity.this, "授权失败，请前往系统设置手动授权,否则会影响抢单效率！");
                }
            }
        }).start();
    }

}
